package com.songyang.serialize;

import com.songyang.serialize.inter.YoungSqlSerialize;
import com.songyang.transport.YoungSQLDataPackage;
import com.songyang.utils.ByteUtils;

import java.util.Arrays;

/**
 * @ClassName YoungSqlEncoder
 * @Description youngsql默认自带的解码器
 * @date 2022/12/30 11:42
 * @Author yanceysong
 * @Version 1.0
 */
public class YoungSqlEncoder implements YoungSqlSerialize {
    /**
     * 将包进行序列化。序列化的结构为
     * <p>
     * [1字节]    [2字节]
     * [flag][decoder_type][data]
     *
     * @param p 包裹
     * @return 序列化的结果
     */

    @Override
    public byte[] serialize(YoungSQLDataPackage p) {
        if (p.getErr() != null && p.getErr().length() > 0) {
            return ByteUtils.concat(new byte[]{1}, ByteUtils.EncoderType2Byte(p.getEncoderType()), ByteUtils.string2Byte(p.getErr()));
        }
        return ByteUtils.concat(new byte[]{0}, ByteUtils.EncoderType2Byte(p.getEncoderType()), ByteUtils.string2Byte(p.getData()));
    }

    /**
     * 按照特定规则反序列化
     *
     * @param raw 序列化好的数据
     * @return 结果
     */
    @Override
    public YoungSQLDataPackage deserialize(byte[] raw) {
        return YoungSqlSerialize.dataIsError(raw) ? new YoungSQLDataPackage(null, new String(Arrays.copyOfRange(raw, DATA_OFFSET, raw.length)), YoungSqlSerialize.getDecoderType(raw)) :
                new YoungSQLDataPackage(new String(Arrays.copyOfRange(raw, DATA_OFFSET, raw.length )), null, YoungSqlSerialize.getDecoderType(raw));
    }
}
